package cn.nxcoder.blog.controller.admin;

import cn.nxcoder.blog.entity.Blog;
import cn.nxcoder.blog.entity.Tag;
import cn.nxcoder.blog.service.BlogService;
import cn.nxcoder.blog.service.TagService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 博客标签Controller
 * @author shengwu ni
 * @date 2018/05/05 21:45
 */
@Controller
@RequestMapping("/admin")
public class TagController {

    @Resource
    private TagService tagService;
    @Resource
    private BlogService blogService;

    /**
     * 分页查询博客标签
     * @param page 第几页
     * @param model 保存查到的记录
     * @return String
     */
    @GetMapping("/tags")
    public String tagList(@RequestParam(defaultValue = "1") Integer page, Model model) {
        // 每页显示5条记录
        PageHelper.startPage(page, 5);
        List<Tag> list = tagService.findAll();
        PageInfo<Tag> pageInfo = new PageInfo<>(list);
        model.addAttribute("page", pageInfo);
        return "admin/tags";
    }

    /**
     * 新增标签跳转接口
     * @return String
     */
    @GetMapping("/tags/input")
    public String input(Model model) {
        model.addAttribute("tag", new Tag());
        return "admin/tags-input";
    }

    /**
     * 新增或更新博客标签
     * @param tag 博客标签实体，需要校验的
     * @param result 校验的结果
     * @param attributes 用于重定向带数据到前端
     * @return String
     */
    @PostMapping("/addOrUpdateTags")
    public String post(@Valid Tag tag, BindingResult result, RedirectAttributes attributes) {

        // 如果tag中的name校验为空（在实体中有注解校验），会重定向到tags-input页，并且会把错误消息带过去
        if (result.hasErrors()) {
            return "/admin/tags-input";
        }

        // 业务上校验，新增的标签名称不能和已有的重复
        Tag tagByName = tagService.findBy("name", tag.getName());
        if (tagByName != null) {
            result.rejectValue("name", "nameError", "该标签名称已经存在，不能重复添加");
            return "/admin/tags-input";
        }

        Integer r;
        if (tag.getId() == null) {
            r = tagService.save(tag);
        } else {
            r = tagService.update(tag);
        }

        // 对插入数据库的操作进行校验，验证是否正常插入或更新了
        if (r == null) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return "redirect:/admin/tags";
    }

    /**
     * 编辑博客标签
     * @param id 标签id
     * @param model 将查询到的标签实体带到前端
     * @return String
     */
    @GetMapping("/tags/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {
        model.addAttribute("tag", tagService.findById(id));
        return "admin/tags-input";
    }

    /**
     * 删除博客标签
     * @param id 标签id
     * @param attributes 用于重定向带数据到前端
     * @return
     */
    @GetMapping("/tags/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes) {

        // 如果标签下有博客，需要将该标签从某个博客中移除
        Tag tag = tagService.findById(id);
        String blogids = tag.getBlogid();
        if (blogids != null && !"".equals(blogids)) {
            for (String blogid : blogids.split(",")) {
                Blog blog = blogService.findById(Long.valueOf(blogid));
                String tagids = blog.getTagid();
                if (tagids.contains("," + tag.getId() + ",")) {
                    tagids = tagids.replace("," + tag.getId() + ",", ",");
                } else if (tagids.contains("," + tag.getId())) {
                    tagids = tagids.replace("," + tag.getId(), "");
                } else if (tagids.contains(tag.getId() + ",")) {
                    tagids = tagids.replace(tag.getId() + ",", "");
                } else if (tagids.equals(tag.getId() + "")) {
                    tagids = "";
                } else {
                }
                blog.setTagid(tagids);
                blogService.update(blog);
            }
        }

        // 如果该标签下没有博客则直接删除
        Integer res = tagService.deleteById(id);
        if (res != null) {
            attributes.addFlashAttribute("message", "操作成功");
        } else {
            attributes.addFlashAttribute("message", "操作失败");
        }
        return "redirect:/admin/tags";
    }
}
